<?php

namespace app\common\model;

use app\common\model\Members;
use app\common\model\Cashs;
use app\common\model\Goods;
use app\common\model\Integrals;
use app\index\model\Addresss;

////微信调用
//use wxpay\database\WxPayResults;
//use wxpay\database\WxPayUnifiedOrder;
//use wxpay\NativePay;
//use wxpay\WxPayApi;
//use wxpay\WxPayConfig;
//use think\Db;

/**
 *  订单表
 */
class Orders extends Base
{

    /**
     * 初始化
     */
    private $wxpayConfig;
    private $wxpay;

    public function _initialize()
    {
        Loader::import('wxpay.lib.WxPayConfig');
        Loader::import('wxpay.lib.WxPayData', EXTEND_PATH);
        Loader::import('wxpay.lib.WxPayApi', EXTEND_PATH);
        Loader::import('wxpay.lib.WxPayNotify', EXTEND_PATH);
        Loader::import('wxpay.lib.WxPayNativePay', EXTEND_PATH);
        Loader::import('wxpay.example.log', EXTEND_PATH);
        error_reporting(E_ERROR);
        Loader::import('wxpay.example.phpqrcode.phpqrcode');
        Loader::import('wxpay.example.notify');
    }

    /**
     * 获取列表
     */
    public function getAll($where = null)
    {
        return $this->where($where)->order('id', 'asc')->select()->toArray();
    }

    /**
     * 会员获取订单列表
     */
    public function getMenmberOrder($where = null)
    {
        return $this->where($where)->group('code')->order('id', 'desc')->select()->toArray();
    }

    /**
     * 会员获取订单列表
     */
    public function getOrderOne($where)
    {
        return $this->where($where)->order('id', 'desc')->select();
    }

    /**
     *  获取会员订单列表
     * @return type
     */
    public function getOrderAll($where, $group = 'code')
    {
        return $this->where($where)->group($group)->order('id', 'desc')->select();
    }

    /**
     *  获取所有列表
     * @return type
     */
    public function getShopAll($where)
    {
        return $this->where($where)->order('id', 'asc')->select();
    }

    public function getlist($page, $size, $where = "", $order = 'id desc')
    {
        return $this->where($where)->order($order)->page($page, $size)->select()->toArray();
    }

    public function buy()
    {
        $code    = input("post.code"); //订单编号
        $address = input("post.address"); //发送地址
        $zhifu   = input("post.zhifu"); //支付方式
        $uncode  = input("post.uncode");
        $add     = new Addresss();
        $dizhi   = $add->getById($address);
        $shdz    = $dizhi->sheng . "" . $dizhi->shi . "" . $dizhi->xian . "" . $dizhi->address;
        if (isset(session('member_info')->id))//证明已经登录
        {
            $s       = $this->getAll("uncode={$uncode}");
            $zongjia = 0;   //获取总价
            foreach ($s as $v)
            {
                $zongjia+=$v['totalmoney'];
            }
            //修改订单地址和tmp
            $arr = [
                'address'  => $shdz,
                'receiver' => $dizhi->receiver,
                'phone'    => $dizhi->phone,
                'tmp'      => 2,
            ];
            $this->where('uncode', $uncode)->update($arr);
            if ($zhifu == 1)
            {
                //修改支付方式,订单状态，积分
                $array = [
                    'paymentmethod' => $zhifu,
                    'status'        => 2,
                    'ispay'         => 2
                ];
                $this->where('uncode', $uncode)->update($array);
                return js_return(1, '支付成功!', []);
            }
            else
            {
                //修改支付方式,订单状态，积分
                $array = [
                    'paymentmethod' => $zhifu,
                    'status'        => 2,
                    'ispay'         => 2
                ];
                $this->where('uncode', $uncode)->update($array);
                $arr   = [
                    'code'    => $code,
                    'zongjia' => $zongjia,
                ];
                $pic   = self::wxpay($arr); //微信支付
                return js_return(4, $pic);
            }
        }
        else
        {
            return js_return(2, '请先登录!', []);
        }
    }

    /**
     * 获取订单信息
     */
    public function getById($val, $field = 'id')
    {
        return (Object) $this->where($field, $val)->find()->toArray();
    }

    /**
     * 删除订单信息但保留数据库中的数据
     */
    public function del()
    {
        $id     = input('id');
        $result = $this->where('id', $id)->setField('scdel', 2);
        if (false !== $result)
        {
            return [1, "删除成功:" . input('id')];
        }
        else
        {
            return [0, $this->getError()];
        }
    }

    /**
     * 删除订单信息
     */
    public function deletes()
    {
        $id     = input('id');
        $result = $this->where("id={$id} or id={$id}")->delete();
        if (false !== $result)
        {
            return [1, "删除成功:" . input('id')];
        }
        else
        {
            return [0, $this->getError()];
        }
    }

    /**
     * 获取josn用到的列表
     */
    public function getOrdersList($type)
    {
        $page  = input('get.page');
        $limit = input('get.limit');
        $where = "scdel=1";

        if (input('get.key/a'))
        {
            foreach (input('get.key/a') as $k => $v)
            {
                if (!empty($v))
                {
                    switch ($k)
                    {
                        case "code":
                            $where .= " and {$k} like '%{$v}%'";
                            break;
                        case "receiver":
                            $where .= " and {$k} like '%{$v}%'";
                            break;
                    }
                }
            }
        }
        if ($type == 1)
        {//分页
            return $this->where($where)->page($page, $limit)->select()->toArray();
        }
        else
        {//总数
            return $this->where($where)->select()->toArray();
        }
    }

    /**
     * 获取csv格式数据
     * 
     */
    public function getExcelAllCsv()
    {
        $where = "scdel=1";
        $where .= input('code') == '' ? '' : " and code like '%" . input('code') . "%'";
        $where .= input('receiver') == '' ? '' : " and receiver like '%" . input('receiver') . "%'";

        //拼接导出Excel数据格式：$rs['cols'=>['name','length'],'data'=>[]];
        $data        = $this->where($where)->select()->toArray();
        $rs          = [
            'cols' => [
                '编号',
                '订单编号',
                '收货人',
                '收货人联系方式',
                '订单总价',
                '订单状态',
                '发起时间',
            ],
            'data' => []
        ];
        $appointment = [];
        foreach ($data as $k => $v)
        {
            $v['code'].="\t";
            $v['time'].="\t";
            $rs['data'][] = [$v['id'], $v['code'], $v['receiver'], $v['phone'], $v['totalmoney'], order_status($v['status']), $v['time']];
        }
        return $rs;
    }

    /**
     * 商家页面获取josn用到的列表
     */
    public function getShopOrdersList($type)
    {
        $page   = input('get.page');
        $limit  = input('get.limit');
        $shopid = session('my_shopself')['id'];
        $where  = "status!=1 and shopid = $shopid";
        if (input('get.key/a'))
        {
            foreach (input('get.key/a') as $k => $v)
            {
                if (!empty($v))
                {
                    switch ($k)
                    {
                        case "code":
                            $where .= " and {$k} like '%{$v}%'";
                            break;
                        case "receiver":
                            $where .= " and {$k} like '%{$v}%'";
                            break;
                        case "status":
                            $where .= " and {$k} = '{$v}'";
                            break;
                    }
                }
            }
        }
        if ($type == 1)
        {//分页
            return $this->where($where)->group('code')->page($page, $limit)->select()->toArray();
        }
        else
        {//总数
            return $this->where($where)->group('code')->select()->toArray();
        }
    }

    /**
     * 获取商家csv格式数据
     * 
     */
    public function getShopExcelAllCsv()
    {
        $where = 'ispay = 2';
        $where .= input('code') == '' ? '' : " and code like '%" . input('code') . "%'";
        $where .= input('receiver') == '' ? '' : " and receiver like '%" . input('receiver') . "%'";

        //拼接导出Excel数据格式：$rs['cols'=>['name','length'],'data'=>[]];
        $data        = $this->where($where)->select()->toArray();
        $rs          = [
            'cols' => [
                '编号',
                '订单编号',
                '收货人',
                '收货人联系方式',
                '订单总价',
                '订单状态',
                '发起时间',
            ],
            'data' => []
        ];
        $appointment = [];
        foreach ($data as $k => $v)
        {
            $v['code'].="\t";
            $v['time'].="\t";
            $rs['data'][] = [$v['id'], $v['code'], $v['receiver'], $v['phone'], $v['totalmoney'], order_status($v['status']), $v['time']];
        }
        return $rs;
    }

    /**
     * 总后台订单发货页面获取josn用到的列表
     */
    public function getZongOrdersList($type)
    {
        $page  = input('get.page');
        $limit = input('get.limit');
        $where = "status!=1 and tmp=2";
        if (input('get.key/a'))
        {
            foreach (input('get.key/a') as $k => $v)
            {
                if (!empty($v))
                {
                    switch ($k)
                    {
                        case "code":
                            $where .= " and {$k} like '%{$v}%'";
                            break;
                        case "receiver":
                            $where .= " and {$k} like '%{$v}%'";
                            break;
                        case "status":
                            $where .= " and {$k} = '{$v}'";
                            break;
                    }
                }
            }
        }
        if ($type == 1)
        {//分页
            return $this->where($where)->page($page, $limit)->order("id desc")->select()->toArray();
        }
        else
        {//总数
            return $this->where($where)->select()->toArray();
        }
    }

    /**
     * 分页
     */
    public function getPageDetile($where, $order, $num)
    {
        return $this->where($where)->group('code')->order($order, 'desc')->paginate($num, false, ['query' => request()->param()]);
    }

    /**
     * 退款
     */
    public function tuikuan()
    {
        $code    = input("code");
        $result  = $this->where('code', $code)->update(['refund' => '2']);
        $cashs   = new Cashs();
        $cashtab = $cashs->getCodeDetails($code);
        $member  = session('member_info');
        $admin   = session('my_shopself');
        /**  现金表相关操作 start */
        $xianjin = [
            'mid'    => $cashtab['mid'], //会员id
            'mname'  => $cashtab['mname'], //会员名称
            'cid'    => $admin['id'], //操作人id
            'cname'  => $admin['mname'], //操作人名称
            'c_type' => 2, //操作人类别
            'money'  => $cashtab['money'], //钱数
            'trend'  => 1, //1收入2支出
            'type'   => 2, //现金类别
            'note'   => $admin['mname'] . "给" . $member->mname . "退款了" . $cashtab['money'] . "元", //描述
            'code'   => $code, //订单编号
            'date'   => date('Y-m-d'),
            'time'   => date('Y-m-d H:i:s'),
        ];
        $cash    = $cashs->add($xianjin); //现金表插入数据
        /**  现金表相关操作 end */
        if (false !== $result)
        {
            return js_return(1, "退款成功");
        }
        else
        {
            return js_return(0, $this->getError());
        }
    }

    /**
     * 删除订单
     */
    public function orderdel($uncode)
    {
        $result = $this->where("uncode = {$uncode}")->delete();
        if (false !== $result)
        {
            return js_return(1, "删除成功", []);
        }
        else
        {
            return js_return(0, "删除失败", []);
        }
    }

    /**
     * 确认收货
     */
    public function ordershouhuo($code)
    {
        $member = session('member_info');
        $mid    = $member->id;
        //增加产品销量
        $order  = $this->getAll("mid = {$mid} and code = {$code}");
        $arr[]  = [];
        foreach ($order as $k => $v)
        {
            $arr[$k][] = $v['g_id'];
            $arr[$k][] = $v['number'];
        }
        //27-4   6-2
        foreach ($arr as $k => $vv)
        {
            $goods = new Goods();
            $gid   = $vv[0];
            $num   = $vv[1];
            $rs    = $goods->getAll("id = {$gid}");
            $goods->update(['sales_num' => $rs[0]['sales_num'] + $num], 'id=' . $gid);
        }
        //确认收货
        $result = $this->where('code', $code)->setField('status', 5);
        if (false !== $result)
        {
            return [1, "操作成功:" . input('id')];
        }
        else
        {
            return [0, $this->getError()];
        }
    }

    /**
     * 申请退款
     */
    public function ordertuihuo($code, $type)
    {
        //确认收货
        $array  = [
            'status'    => 3,
            'backgoods' => $type
        ];
        $result = $this->where('code', $code)->update($array);
        if (false !== $result)
        {
            return [1, "操作成功:" . input('id')];
        }
        else
        {
            return [0, $this->getError()];
        }
    }

    /**
     * 取消退款
     */
    public function cancel($code, $type)
    {
        if ($type == 1)
        {
            $arr = [
                'status' => 5,
                'refund' => 1,
            ];
        }
        else
        {
            $arr = [
                'status' => 2,
                'refund' => 1,
            ];
        }
        $result = $this->where('code', $code)->update($arr);
        if (false !== $result)
        {
            return [1, "取消成功:" . input('id')];
        }
        else
        {
            return [0, $this->getError()];
        }
    }

    /**
     * 退款删除订单
     */
    public function tuikuandel($code)
    {
        $result = $this->where("code = {$code}")->delete();
        if (false !== $result)
        {
            return js_return(1, "删除成功", []);
        }
        else
        {
            return js_return(0, "删除失败", []);
        }
    }

    /**
     * 订单详情获取列表
     */
    public function getOrderDetail($where)
    {
        return $this->where($where)->order('id', 'asc')->select();
    }

    /**
     * 导出excel数据格式
     */
    public function excelData($page)
    {
        $shopid = session('my_shopself')['id'];
        $where  = "status!=1 and shopid = $shopid";
        $s      = new self();
        $rs     = $s->getLists($where, $page, "id,code,receiver,phone,totalmoney,status,time");
        foreach ($rs as $k => $v)
        {
            $rs[$k]['status'] = order_status($v['status']);
        }
        return $rs;
    }

    /**
     * 商家列表导出excel用到的数据
     */
    public function getLists($wheres = '', $pages = 1, $fields = '*', $order = ['id' => 'desc'])
    {
        $page  = input('get.page', $pages);
        $limit = input('get.limit');
        return $this->where($wheres)->group('code')->page($page, $limit)->field($fields)->order($order)->select()->toArray();
    }

    //二维码
    static public function wxpay($arr)
    {
//        p(\WxPayUnifiedOrder::class);
        import('wxpay.lib.WxPayData',EXTEND_PATH);
        $notify = new \NativePay();
        $input  = new \WxPayUnifiedOrder();
        $input->SetBody("test");
        $input->SetAttach("test");
        $input->SetOut_trade_no("sdkphp123456789" . date("YmdHis"));
        $input->SetTotal_fee("1");
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id("123456789");

        $result = $notify->GetPayUrl($input);
        $url2   = $result["code_url"];
        p($url2);
        return $qrCode_url;
    }

}
